package com.pituruh.tjroute;

import java.net.URL;

import java.util.ArrayList;
import java.util.Calendar;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.pituruh.utils.FindRouteRecord;
import com.pituruh.utils.FindRouteSitesList;
import com.pituruh.utils.FindRouteXMLHandler;
import com.pituruh.utils.ShelterSitesList;
import com.pituruh.utils.ShelterXMLHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class FindRoute extends Activity implements Runnable {
	/** Create Object For SiteList Class */
	ShelterSitesList sitesList = null;
	ArrayList<String> listItems = null;
	FindRouteRecord findRoute;
	private int mHour = 0;
	private int mMinute = 0;

	static final int TIME_DIALOG_ID = 0;
	private TimePickerDialog.OnTimeSetListener mTimeSetListener;
	/*private ProgressDialog pd;*/
	ProgressBar pb;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_route);

		Resources res = getResources();
		int colors[] = { res.getColor(R.color.actionbar_color_1),
				res.getColor(R.color.actionbar_color_2) };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		LinearLayout layout = (LinearLayout) findViewById(R.id.buttonlayout);
		layout.setBackgroundDrawable(grad);

		TextView title_bar = (TextView) findViewById(R.id.title_bar);
		title_bar.setText(R.string.pencarian_rute);

		findRoute = new FindRouteRecord();

		mTimeSetListener =
			new TimePickerDialog.OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int mHour, int mMinute) {
				TextView mTimeDisplay = (TextView) findViewById(R.id.jam_keberangkatan);

				mTimeDisplay.setText(
						new StringBuilder()
						.append(pad(mHour)).append(":")
						.append(pad(mMinute)));
			}
		};

		/****progress dialog***/
/*		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_data_from_server), true,
				false);
*/		pb = (ProgressBar) findViewById(R.id.title_progress);
		pb.setVisibility(View.VISIBLE);

		Thread thread = new Thread(this);
		thread.start();
		/****end of progress dialog***/
	}

	public void run() {
		try {
			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
			"http://transjogja.only.web.id/app/xml/shelter.xml");


			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			ShelterXMLHandler myXMLHandler = new ShelterXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

			/** Get result from MyXMLHandler SitlesList Object */
			sitesList = ShelterXMLHandler.sitesList;
			//		FindRouteSitesList sitesList1 = FindRouteXMLHandler.sitesList;

			listItems = new ArrayList<String>();
			for (int i = 0; i < sitesList.getName().size(); i++) {
				listItems.add(sitesList.getName().get(i));
			}

		} catch (Exception e) {
			System.out.println("XML Parsing Exception = " + e);
		}
		handler.sendEmptyMessage(0);
		
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			/*pd.dismiss();*/
			pb.setVisibility(View.GONE);
			
			if (listItems == null) {
				Toast.makeText(getApplicationContext(), R.string.failed_loading, Toast.LENGTH_SHORT)
							.show();
				finish();
			}
			else {
				fillSpinner();
			}
		}
	};
	
	private void fillSpinner() {
		Spinner spinner = (Spinner) findViewById(R.id.jenis_pencarian);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.arr_jp, android.R.layout.simple_spinner_item);

		adapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
	}

/*	public void onStart() {
		super.onStart();
		
		Spinner spinner = (Spinner) findViewById(R.id.jenis_pencarian);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.arr_jp, android.R.layout.simple_spinner_item);

		adapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}
*/	
	public void onHomeClick(View v) {
		startActivity(new Intent(FindRoute.this, TJRoute.class));
	}

	public void onCariClick(View v) {
		// startActivity(new Intent(FindRoute.this, FindRoute.class));
		//		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
		//				.show();
	}

	public void onFindClick(View v) {
		startActivity(new Intent(FindRoute.this, FindRouteResult.class));
	}

	public void onPOIAwalClick(View v) {
		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
		.show();
	}

	public void onGPSAwalClick(View v) {
		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
		.show();
	}

	public void onGmapAwalClick(View v) {
		Intent newIntent = new Intent(this.getApplicationContext(),
				ChooseShelter.class);
		int activityID = 0x100;
		newIntent.putExtra("selectedShelter",findRoute.getStartShelter());
		startActivityForResult(newIntent, activityID);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0x100: {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				TextView tStart = (TextView) findViewById(R.id.shelter_awal);
				tStart.setText(extras.getString("selectedShelter"));
				findRoute.setStartShelter(extras.getString("selectedShelter"));
			}
			break;
		}
		case 0x101: {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				TextView tStop = (TextView) findViewById(R.id.shelter_tujuan);
				tStop.setText(extras.getString("selectedShelter"));
				findRoute.setStopShelter(extras.getString("selectedShelter"));
			}
			break;
		}
		}
	}

	public void onListAwalClick(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.choose_shelter);
		builder.setIcon(R.drawable.list);

		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item, listItems);

		int itemIndex = -1;
		if (findRoute.getStartShelter() != null)
			itemIndex = listItems.indexOf(findRoute.getStartShelter());
		builder.setSingleChoiceItems(spinnerArrayAdapter, itemIndex,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				findRoute.setStartShelter(listItems.get(item));
				TextView tStart = (TextView) findViewById(R.id.shelter_awal);
				tStart.setText(listItems.get(item));
				// Toast.makeText(getApplicationContext(),
				// listItems.get(item), Toast.LENGTH_SHORT).show();
				dialog.dismiss();
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	public void onPOITujuanClick(View v) {

		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
		.show();
	}

	public void onGPSTujuanClick(View v) {
		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
		.show();
	}

	public void onGmapTujuanClick(View v) {
		Intent newIntent = new Intent(this.getApplicationContext(),
				ChooseShelter.class);
		int activityID = 0x101;
		newIntent.putExtra("selectedShelter",findRoute.getStopShelter());
		startActivityForResult(newIntent, activityID);

		/*		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
				.show();
		 */	}

	public void onListTujuanClick(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.choose_shelter);
		builder.setIcon(R.drawable.list);

		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item, listItems);

		int itemIndex = -1;
		if (findRoute.getStopShelter() != null)
			itemIndex = listItems.indexOf(findRoute.getStopShelter());
		builder.setSingleChoiceItems(spinnerArrayAdapter, itemIndex,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				findRoute.setStopShelter(listItems.get(item));
				TextView tStop = (TextView) findViewById(R.id.shelter_tujuan);
				tStop.setText(listItems.get(item));
				// Toast.makeText(getApplicationContext(),
				// listItems.get(item), Toast.LENGTH_SHORT).show();
				dialog.dismiss();
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
		/*		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
				.show();
		 */	}

	public void onTimeClick(View v) {
		// get the current time
		showDialog(TIME_DIALOG_ID);

		if (mHour == 0 && mMinute == 0) {
			final Calendar c = Calendar.getInstance();
			mHour = c.get(Calendar.HOUR_OF_DAY);
			mMinute = c.get(Calendar.MINUTE);

			// display the current date
			updateDisplay();
		}
	}

	// updates the time we display in the TextView
	private void updateDisplay() {
		TextView mTimeDisplay = (TextView) findViewById(R.id.jam_keberangkatan);

		mTimeDisplay.setText(
				new StringBuilder()
				.append(pad(mHour)).append(":")
				.append(pad(mMinute)));
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this,
					mTimeSetListener, mHour, mMinute, false);
		}
		return null;
	}
}
